package cn.xiaoliu.pet.controller;

import cn.xiaoliu.basic.exception.BusinessException;
import cn.xiaoliu.basic.utils.AjaxResult;
import cn.xiaoliu.basic.utils.LoginContext;
import cn.xiaoliu.basic.utils.PageList;
import cn.xiaoliu.org.domain.Shop;
import cn.xiaoliu.org.query.ShopQuery;
import cn.xiaoliu.pet.domain.Pet;
import cn.xiaoliu.pet.query.PetQuery;
import cn.xiaoliu.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;

    @PostMapping
    public PageList<Pet> queryPage(@RequestBody PetQuery query){

        return petService.queryPage(query);
    }

    /**
     * 宠物上架
     * @param ids
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onsale(@RequestBody List<Long> ids){
        try {
            petService.onsale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("业务繁忙，稍后重试");
        }
    }

    /**
     * 宠物下架
     * @param ids
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offsale(@RequestBody List<Long> ids){
        try {
            petService.offsale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("业务繁忙，稍后重试");
        }
    }

    /**
     * 查询宠物的基本信息和详情信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Pet queryById(@PathVariable("id") Long id){
        return petService.queryByIdDetail(id);
    }

    /**
     * 购买宠物
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/toBuy/{id}")
    public AjaxResult toBuy(@PathVariable("id") Long id, HttpServletRequest request){
        petService.toBuy(id,LoginContext.getLogininfo(request));
        return AjaxResult.me();
    }

}
